<template>
  <a-modal
    v-model:open="openEditUser"
    title="编辑用户信息"
    ok-text="保存"
    cancel-text="取消"
    @ok="editUser"
  >
    <a-form layout="horizontal" :model="editUserParam" style="max-width: 600px">
      <a-form-item label="用户昵称">
        <a-input v-model:value="editUserParam.userName" placeholder="输入昵称" allow-clear />
      </a-form-item>

      <!--上传头像组件-->
      <a-form-item label="用户头像">
        <PictureUpload :picture="picture" :user-avatar="true" :on-success="onSuccess"/>
      </a-form-item>



      <a-form-item label="用户简介">
        <a-textarea :rows="4" v-model:value="editUserParam.userProfile" />
      </a-form-item>
      <a-form-item label="用户权限">
        <a-radio-group v-model:value="editUserParam.userRole">
          <a-radio value="user">普通用户</a-radio>
          <a-radio value="admin">管理员</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { defineExpose, reactive, ref } from 'vue'
import { updateUserUsingPost } from '@/api/userController.ts'
import { message, type UploadProps } from 'ant-design-vue'
import PictureUpload from '@/components/PictureUpload.vue'


// 头像上传所需变量
const picture = ref<API.PictureVO>({})

const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  editUserParam.value.userAvatar = picture.value.url
}

const openEditUser = ref<boolean>(false)
let editUserParam = ref<API.UserUpdateRequest>({})

// 获取父组件方法
const emit = defineEmits(['refresh'])

// 打开对话框
const openDialog = (params: API.UserUpdateRequest) => {
  console.log(params)
  editUserParam.value = params
  picture.value.url = params.userAvatar
  openEditUser.value = true
}

/**
 *  编辑用户
 */
const editUser = async () => {
  const res = await updateUserUsingPost(editUserParam.value)
  if (res.data.code === 0 && res.data.data) {
    editUserParam.value = {
      id: 0,
      userName: '',
      userProfile: '',
      userAvatar: '',
      userRole: '',
    }
    openEditUser.value = false
    message.success('修改成功')
    // 调用父组件的方法
    await emit('refresh')
  } else {
    message.error('修改失败，' + res.data.message)
  }
  openEditUser.value = false
}




// 暴露方法
defineExpose({
  openDialog,
})
</script>

<style scoped>
#picture-upload :deep(.ant-upload) {
  width: 100px;
  height: 100px;
  max-width: 152px;
  max-height: 152px;
  overflow: hidden;
}

#picture-upload img {
  max-width: 152px;
  max-height: 152px;
}



</style>
